package com.lagou;

import com.lagou.handler.UserServerHandler;
import com.lagou.service.UserService;
import com.lagou.service.po.RpcRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * create by tanxh on 2020-05-22
 **/

@Component("rpcProvider")
public class RPCProvider{
    private static ApplicationContext applicationContext;
    @Autowired
    public UserService userService;

    public Object createProxy(RpcRequest rpcRequest) throws ClassNotFoundException {
        Class<?> clazz = Class.forName(rpcRequest.getClassName());
        Object proxyInstance = Proxy.newProxyInstance(UserServerHandler.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public String invoke(Object o, Method method, Object[] objects) throws Throwable {
                String responseMsg = "";
                if (clazz == UserService.class) {
                    Method declaredMethod = clazz.getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                    String result = (String)declaredMethod.invoke(userService, rpcRequest.getParameters());
                    System.out.println("反射调用成功，result=" + result);
                    responseMsg = "success！" + result;
                }
                return responseMsg;
            }
        });

        return proxyInstance;
    }


}
